<?php
use com\masfletes\db\DBUtil;

class OperationController_ScheduleController extends JController {

    private $userSessionId;
    
     public function init() {
        parent::init();
        if (!Model3_Auth::isAuth()) {
            $this->redirect('Index/index');
        }
        $this->userSessionId = $_SESSION['USERSESSIONID'];
    }
    
    public function indexAction() {
        //Solo el Index se devuelve de manera normal(text/html)
        $this->setResponseJSON(FALSE);
        
        //Includes específicos de esta página        
        $this->view->customScripts .= $this->view->getJsManager()->loadJsFile('application/OperationController/Schedule/schedulesApp.js', false, TRUE);
        $this->view->getJsManager()->addJsVarEncode('contextPath', $this->view->url(array('controller' => 'Schedule')));
        $this->view->getJsManager()->addJsVarEncode('vehicleContextPath', $this->view->url(array('controller' => 'Vehicles')));
        $this->view->getJsManager()->addJsVarEncode('userContextPath',$this->view->url(array('controller' => 'Users')));
        $this->view->getJsManager()->addJsVarEncode('routeContextPath',$this->view->url(array('controller' => 'Routes')));
        $this->view->setTemplate('GeneralContentLayout');
    }
    
    public function getSchedulesAction() {
        $params = $this->getRequest()->getPostJson();
        
        $page = $this->getArrayValue('page', $params);
        $limit = $this->getArrayValue('rowsPerPage', $params);
        $sidx = $this->getArrayValue('sortField', $params);
        $sord = $this->getArrayValue('sortDir', $params);
        $id = $this->getArrayValue('id', $params);
        
        if (!$sidx)
            $sidx = 1;

        try {
            $this->permitirAcceso($this->userSessionId, 'rutas', 'listar');
            $conn = $this->getConnection();

            $parameters = array($this->userSessionId,$page, $limit, $sidx, $sord, $id);
            $resultsets = DBUtil::executeStoredProc($conn, 'sp_schedule_list', $parameters, PDO::FETCH_NAMED);
            unset($conn);
        } catch (PDOException $ex) {
            $errMsg = $ex->getMessage(); //utf8_encode($ex->getMessage());
            if (strpos($errMsg, '50000') > -1) {
                echo json_encode(array("error" => trim(substr($errMsg, strpos($errMsg, '50000') + 5)), "code" => $ex->getCode(), "trace" => $ex->getTraceAsString()));
            } else {
                echo json_encode(array("error" => $errMsg, "code" => $ex->getCode(), "trace" => $ex->getTraceAsString()));
            }
            return;
        } catch (Exception $generalEx) {
            echo json_encode(array("error" => $generalEx->getMessage(), "code" => $generalEx->getCode(), "trace" => $generalEx->getTraceAsString()));
            return;
        }
        echo json_encode($resultsets);
    }
    
    public function saveAction(){
        $params = $this->getRequest()->getPostJson();
        $id = $this->getArrayValue('id', $params);
        $route_id = $this->getArrayValue('route_id', $params);
        $vehicle_id = $this->getArrayValue('vehicle_id', $params);
        $user_id = $this->getArrayValue('user_id', $params);
        $start_date = $this->getArrayValue('start_date', $params);
        $status = $this->getArrayValue('status', $params);
        $monday = $this->getArrayValue('monday', $params);
        $tuesday = $this->getArrayValue('tuesday', $params);
        $wednesday = $this->getArrayValue('wednesday', $params);
        $thursday = $this->getArrayValue('thursday', $params);
        $friday = $this->getArrayValue('friday', $params);
        $saturday = $this->getArrayValue('saturday', $params);
        $sunday = $this->getArrayValue('sunday', $params);
        $recurrent = $this->getArrayValue('recurrent', $params);
        $week = $this->getArrayValue('week', $params);
        $scheduleParent_id = $this->getArrayValue('scheduleParent_id', $params);
        
        $start_date_dt = DateTime::createFromFormat('Y-m-d H:i:s', $start_date);
        try {
            $this->permitirAcceso($this->userSessionId, 'rutas', ($id==null) ? 'agregar' : 'editar');
            
            $conn = $this->getConnection();
            $parameters = array($id, $route_id, $vehicle_id, $user_id, $start_date, $status, $monday, $tuesday, $wednesday, $thursday, $friday, $saturday, $sunday, $recurrent, $week, $scheduleParent_id);
            $resultsets = DBUtil::executeStoredProc($conn, 'sp_schedule_save', $parameters, PDO::FETCH_NAMED);
            unset($conn);
        } catch (Exception $ex) {
            $errMsg = utf8_encode($ex->getMessage());
            if (strpos($errMsg, '50000') > -1) {
                echo json_encode(array("error" => trim(substr($errMsg, strpos($errMsg, '50000') + 5)), "code" => $ex->getCode(), "trace" => $ex->getTraceAsString()));
            } else {
                echo json_encode(array("error" => $errMsg, "code" => $ex->getCode()/*, "trace" => $ex->getTraceAsString()*/));
            }
            return;
        }
        echo json_encode($resultsets);
    }
    
    public function deleteAction() {
          $params = $this->getRequest()->getPostJson();
          $id = $params['id'];
          if($id==null)
                return;
          try {
            $this->permitirAcceso($this->userSessionId, 'rutas', 'eliminar');
            
            $conn = $this->getConnection();
            $parameters = array($id);
            $resultsets = DBUtil::executeStoredProc($conn, 'sp_schedule_delete', $parameters, PDO::FETCH_NAMED);
            unset($conn);
        } catch (Exception $ex) {
            $errMsg = /*utf8_encode(*/$ex->getMessage()/*)*/;
            if (strpos($errMsg, '50000') > -1) {
                echo json_encode(array("error" => trim(substr($errMsg, strpos($errMsg, '50000') + 5)), "code" => $ex->getCode(), "trace" => $ex->getTraceAsString()));
            } else {
                if(strpos($errMsg,'FK_')>-1){
                    echo json_encode(array("error" => "Existen registros relacionados. No es posible eliminar el registro actual"));                
                }else {
                    echo json_encode(array("error" => $errMsg, "code" => $ex->getCode()/*, "trace" => $ex->getTraceAsString()*/));                
                }
            }
            return;
        }
        echo json_encode($resultsets);
     }
}